import groovy.mock.interceptor.StubFor
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

class FetchServiceTests extends GroovyTestCase {

    def fetchService
    def httpClientStub
    def getMethodStub

    void setUp() {        
        fetchService = new FetchService()
        httpClientStub = new StubFor(HttpClient.class)
        getMethodStub = new StubFor(GetMethod.class)
        httpClientStub.demand.executeMethod() {it}
    }

    void testFetchContent() {
        prepareGetMethod("hi", "utf-8")
	httpClientStub.use {
            getMethodStub.use {
                def result = fetchService.fetchContent('http://test.com')
                assertNotNull result.headers
                assertNotNull result.rawData
                assertNotNull result.headers.charset
            }
        }
    }

    void testFetch() {
        def html = '''
<html>
<head>
<title>mytitle</title>
<link rel="alternate" type="application/atom+xml" title="pphetra - Atom" href="http://myfeed/feed" />
</head>
<body>
hello
</body>
</html>
'''
        prepareGetMethod(html, 'utf-8')
        httpClientStub.use {
            getMethodStub.use {
                def result = fetchService.fetch('http://test.com')
                assertEquals 'http://test.com', result.url
                assertEquals 'mytitle', result.title
                assertEquals 'http://myfeed/feed', result.feeds[0].'@href'
                assert result.html instanceof Node
            }
        }
    }

    void testFetchHeaderWithNoCharset() {
        def html = '''
<html>
<head>
<title>mytitle</title>
<meta http-equiv="Content-Type" content="text/html; charset=tis-620">
<meta http-equiv="Content-Type" content="text/html; charset=windows-874">
</head>
<body>
ไทย
</body>
</html>
'''
        getMethodStub.demand.getResponseBody() {html.getBytes('tis-620')}
        getMethodStub.demand.getResponseCharSet() {'ISO-8859-1'}
        getMethodStub.demand.getResponseHeaders() {
            [[name:'charset',value:'ISO-8859-1'],
            [name: 'Content-Type', value: 'text/html']]
        }
        httpClientStub.use {
            getMethodStub.use {
                def result = fetchService.parseHtml('http://test.com')
                assertEquals 'ไทย', result.html.BODY.text()
                assertEquals 'tis-620', result.content.headers.charset
                
            }
        }
    }


    def prepareGetMethod(body, charset) {
        getMethodStub.demand.getResponseBody() {body.getBytes('utf-8')}
        getMethodStub.demand.getResponseCharSet() {charset}
        getMethodStub.demand.getResponseHeaders() {[[name:'charset',value:charset]]}
    }

}
